<?php
declare (strict_types=1);

namespace app\scan_bag\controller;

use aliyun\AliyunOss;
use app\admin\model\advertiser\AdvertiserThirdLog;
use app\admin\model\base\User;
use app\admin\model\iot\ScanBagWay;
use app\admin\service\base\JwtService;
use app\BaseController;
use app\Request;
use app\scan_bag\service\ScanBagV1Service;
use app\scan_bag\service\ScanBagV2Service;
use app\scan_bag\service\V1_Way_1_0Service;
use think\App;
use think\facade\Cache;
use think\response\Json;
use wechat\WsOfficialAccount;

/**
 * V1微信扫码取袋
 */
class V1_Way_1_0 extends BaseController
{

    /**
     * 无塑地球微信H5用户登录
     * @param ScanBagV2Service $scanBagV2Service
     * @return Json
     */
    public function wsWechatLogin(ScanBagV2Service $scanBagV2Service): Json
    {
        //接受参数
        $code = $this->request->param('code/s', '');
        //微信解析code
        $bool = $scanBagV2Service->wechatH5Login($code);
        if ($bool['bool']) {
            //签发token
            $jst_data = JwtService::authorizations('scan_bag', $bool['user_id'], 3600);
            if ($jst_data['bool']) {
                //返回数据
                return jsonReturn(1, $bool, '登录成功');
            }
        }
        return jsonReturn(0, [], '签发token失败');
    }

    /**
     * 通过设备mac_id获取取袋路径
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function getMacIdWay(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接受参数
        $mac_id = $this->request->param('mac_id/s', '0');
        //获取系统配置
        $data['take_process'] = $v1_Way_1_0Service->take_process;
        $data['current_process'] = 'ws_official_account';
        //查询数据库获取取袋路径
        $WayInfo = ScanBagWay::getMacIdWay($mac_id);
        //e领袋
        if ($WayInfo and isset($WayInfo['key']) and $WayInfo['key'] == 'V1_Way_1_1') {
            $data['current_process'] = 'e_neck_pocket_way';
        }
        //返回数据
        return jsonReturn(1, $data);
    }

    /**
     * 微信H5公众号二维码
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function wechatQrcode(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接受参数
        $subscribe = $this->request->param('subscribe/d', 0);
        $mac_id = $this->request->param('mac_id/s', '0');
        $data = $v1_Way_1_0Service->wechatQrcode($subscribe, $mac_id);
        //返回数据
        return jsonReturn(1, $data);
    }

    /**
     * 微信小程序URLScheme
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function getURLScheme(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接收参数
        $param = $this->request->param();
        return $v1_Way_1_0Service->getURLScheme($param);
    }

    /**
     * 获取JSAPI配置
     * @return Json
     */
    public function jsApiConfig(): Json
    {
        //接受参数
        $url = $this->request->param('url/s', '');
        $obj = new WsOfficialAccount();
        return jsonReturn(1, $obj->getJsApi($url));
    }

    /**
     * 无塑地球微信小程序用户登录
     * @param ScanBagV2Service $scanBagV2Service
     * @return Json
     */
    public function miniProgramLogin(ScanBagV2Service $scanBagV2Service): Json
    {
        //接受参数
        $appid = $this->request->param('appid/s', '');
        $code = $this->request->param('code/s', '');
        //微信解析code
        $bool = $scanBagV2Service->miniProgramLogin($appid, $code);
        if ($bool['bool']) {
            //通过用户id获取取袋token
            $is_token = JwtService::getUserToken('scan_bag', $bool['user_id']);
            if ($is_token) {
                return jsonReturn(1, $bool, '登录成功');
            } else {
                //没有token则签发token
                $jst_data = JwtService::authorizations('scan_bag', $bool['user_id'], 3600);
                if ($jst_data['bool']) {
                    //返回数据
                    return jsonReturn(1, $bool, '登录成功');
                }
            }
        }
        return jsonReturn(0, [], '签发token失败');
    }

    /**
     * 微信上传经纬度信息
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function wechatLatLon(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接受参数
        $mac_id = $this->request->param('mac_id/s', '0');
        $latitude = $this->request->param('latitude/s', '0');
        $longitude = $this->request->param('longitude/s', '0');
        $accuracy = $this->request->param('accuracy/d', 0);    //位置精度
        //经纬度保存数据库
        $user_id = WS_USER_ID;
        //把地理位置信息保存至用户表
        User::userLocationRedis($user_id, $mac_id, $latitude, $longitude);
        //微信验证上传经纬度信息
        $bool = $v1_Way_1_0Service->wechatLatLon($mac_id, $latitude, $longitude);
        if ($bool) {
            return jsonReturn(1, [], '验证通过');
        }
        return jsonReturn(0, [], '您的位置距离设备太远,请移步设备前扫码免费领取。');
    }

    /**
     * 微信获取用户信息
     * @return Json
     */
    public function getUserInfo(): Json
    {
        //默认值
        $user_id = WS_USER_ID;
        $info = User::getIdUserInfo($user_id);
        //处理昵称
        $info['nickname'] = '环保卫士' . substr($info['uuid'], 27, 5);
        //处理头像
        $AliyunOss = new AliyunOss();
        $avatar = $info['avatar'] ?: config('ws_config.avatar');
        $info['avatar'] = $AliyunOss->getObjectUrl(config('ws_config.avatar'));
        return jsonReturn(1, $info);
    }

    /**
     * 微信小程序广告ID
     * @param ScanBagV2Service $scanBagV2Service
     * @return Json
     */
    public function wechatAppletAdvert(ScanBagV2Service $scanBagV2Service): Json
    {
        //接收参数
        $appid = $this->request->param('appid/s', '');
        $data = $scanBagV2Service->miniProgramAdvert($appid);
        if ($data['bool']) {
            return jsonReturn(1, $data['advert']);
        }
        return jsonReturn(0, []);
    }

    /**
     * 获取安全code防止用户跳过关注这一步
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function getSafeCode(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接收参数
        $mac_id = $this->request->param('mac_id', '');
        $step = $this->request->param('step/d', 1);
        //获取取袋安全码
        $key = $v1_Way_1_0Service->getSafeCode($mac_id, $step);
        if (!$key) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码!');
        }
        return jsonReturn(1, []);
    }

    /**
     * 获取用户取袋次数并同步用户到客户
     * @param ScanBagV1Service $scanBagV1Service
     * @return Json
     */
    public function userScanNum(ScanBagV1Service $scanBagV1Service): Json
    {
        //接收参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        return $scanBagV1Service->userScanNum($user_id, $mac_id);
    }

    /**
     * 调物联网接口进行出袋操作
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function postOutBag(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        return $v1_Way_1_0Service->outBagCommon();
    }

    /**
     * 调物联网接口进行出袋操作
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function postOutBag5s(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        return $v1_Way_1_0Service->outBagCommon(10);
    }

    /**
     * 发起微信支付
     * @param ScanBagV1Service $scanBagV1Service
     * @return Json
     */
    public function payOrder(ScanBagV1Service $scanBagV1Service): Json
    {
        $mac_id = $this->request->param('mac_id');
        if (!$mac_id) {
            return jsonReturn(0, [], '设备信息错误');
        }
        return $scanBagV1Service->payOrderToV1(WS_USER_ID, $mac_id);
    }

    /**
     * 验证码票据验证
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function verifyCapture(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接收参数
        $ticket = $this->request->param('ticket/s', '');//验证码票据
        $randstr = $this->request->param('randstr/s', '');//前端回调函数返回的随机字符串
        $user_ip = $this->request->ip();
        $params = array(
            "Ticket" => $ticket,
            "UserIp" => $user_ip,
            'Randstr' => $randstr
        );
        $result = $v1_Way_1_0Service->verifyCapture($params);
        if (isset($result->CaptchaCode) && $result->CaptchaCode == 1) {
            //写入缓存
            $key = 'capture_ticket:' . $ticket;
            Cache::set($key, 1, 500);
            return jsonReturn(1, $result);
        } else {
            return jsonReturn(0, $result);
        }
    }

    /**
     * 判断是否要显示图形验证码
     * @param Request $request
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function showCapture(Request $request, V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        $mac_id = $request->param('mac_id');
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        $result = $v1_Way_1_0Service->showCapture($mac_id);
        if ($result) {
            return jsonReturn(1, ['show_capture' => 1], '');
        } else {
            return jsonReturn(0, ['show_capture' => 0], '');
        }
    }

    /**
     * 微信小程序获取推广小程序
     * @param Request $request
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function wechatPopularizeProgram(Request $request, V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        $mac_id = $request->param('mac_id/s');
        //判断参数
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        return $v1_Way_1_0Service->wechatPopularizeProgram($mac_id);
    }

    /**
     * 微信小程序写入推广统计
     * @return Json
     */
    public function wechatPopularizeWrite(): Json
    {
        $user_id = WS_USER_ID;
        $third_id = $this->request->param('third_id/d', 0);
        $mac_id = $this->request->param('mac_id/s', '');
        //判断参数
        if (!$third_id or !$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        AdvertiserThirdLog::writeMiniprogramLog($user_id, $third_id, $mac_id);
        return jsonReturn(1, []);
    }

    /**
     * 判断是否打开位置限制
     * @param Request $request
     * @return Json
     */
    public function locationLimit(Request $request):Json
    {
        $mac_id = $request->param('mac_id/s','');
        //判断参数
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        //通过mac_id获取路径
        $WayInfo = ScanBagWay::getMacIdWay($mac_id);
        if($WayInfo && $WayInfo['location_limit']){
            return jsonReturn(1, ['location_limit'=>$WayInfo['location_limit']]);
        }
        return jsonReturn(1, ['location_limit'=>0]);
    }

}
